import React, { Component, PropTypes } from 'react';
import {Relax, msg} from 'iflux2';
import {Map, OrderedSet, List} from 'immutable';
import {Link} from 'react-router';
import moment from 'moment'
import {Table, Row, Col, Button, Spin, Icon, message} from 'antd';
import OrderTable from 'components/OrderTable'
import {listQL} from '../ql';
import {orderColumns, renderOrderFilter} from '../constant/columns';
import {orderStatus} from '../constant/order-status';
import Deliver from '../../common/deliver';

import Refund from '../../common/refund';
import noop from 'util/noop';
import classNames from 'classnames';

@Relax
class OrderList extends Component {
    static defaultProps = {
        //数据
        list: listQL,
        filterKey: 'ALL',
        type: 'ALL',
        tradeOrder:Map({}),
        pagination:Map({}),
        expressCompany: List(),
        payAmount:0,
        payTypeBOList:List(),
        //方法处理
        startExportOrder: noop,
        queryOrderList: noop,
        setOrderStatus: noop,
        setPagination:noop,
        resetPagination: noop,
        deliveryOrder: noop,
        copyTrade: noop,
        refund:noop,
        refundBefore:noop,
        cancelOrder:noop,

    };
    constructor(props) {
        super(props);

        //页面滚动控制，翻页时调用
        this.pageWrapper = null;
        this.state = {
            selectedRowKeys: [],
            loading: true,
            activeOrder:Map({}),
            filterDropdownVisible: false,
            deliveryVisible:false,
            refundVisible:false,
            confirmLoading:false,
        }
    }

    componentDidMount() {
        msg.on('setLoading', (loading)=>{
            this.setLoading(loading);
        })

        if(window.document.getElementById("react-content")){
            this.pageWrapper = window.document.getElementById("react-content").getElementsByClassName("page-wrapper")[0];
        }
    }

    scrollTop(){
        if(this.pageWrapper){
            this.pageWrapper.scrollTop = 0;
        }else if(window.document.getElementById("react-content")){
            window.document.getElementById("react-content").getElementsByClassName("page-wrapper")[0].scrollTop = 0;
        }
    }

    render() {
        let {list, type, expressCompany, tradeOrder, pagination, payAmount, payTypeBOList} = this.props;
        let {selectedRowKeys, loading, confirmLoading, deliveryVisible, refundVisible, activeOrder} = this.state;

        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onSelectAll: this.selectAll
        };

        const orderHeader = (<Table 
                                pagination={false}
                                rowSelection={rowSelection}
                                columns={this.renderHeaderColumns()}
                                dataSource={list.toJS()}
                            />);

        // let selectAll = list.filterNot(order=>OrderedSet(selectedRowKeys).has(order.get('tid'))).isEmpty();
        // let indeterminate = !selectAll && !OrderedSet(selectedRowKeys).isEmpty();
        const listRowSelection = {
            selectedRowKeys: selectedRowKeys,
            onChange:this.handleSelect,
        }

        const page = {
            current:pagination.get('pageNum'),
            total:pagination.get('totalCount'),
            pageSize:pagination.get('pageSize'),
            onChange:this.changePageNum,
            onShowSizeChange:this.changePageSize,
            showTotal:(total)=>`共${total}条`,
            showQuickJumper: true,
            showSizeChanger: true,
        }
        return (
            <div>
                {this.renderToolBar()}
                <OrderTable 
                    loading={loading}
                    rowKey='tid'
                    hideKey="itemOrders"
                    rowSelection={listRowSelection}
                    header={orderHeader}
                    rowHeader={this.renderRowHeader}
                    dataSource={list.toJS()}
                    columns={this.renderSubColumns()}
                    pagination={page}
                />
                <Deliver 
                    order={activeOrder}
                    visible={deliveryVisible}
                    confirmLoading={confirmLoading}
                    expressCompany={expressCompany}
                    onOk={(values)=>this.deliveryOrder(values)}
                    onCancel={this.cancelDeliveryOrder}
                />
                <Refund 
                    tradeOrder={tradeOrder}
                    payAmount={payAmount}
                    payTypeBOList={payTypeBOList}
                    visible={refundVisible}
                    showModal={this.showRefundModal}
                    onOk={this.reimburse}
                />
            </div>
        );
    }
    /*
     * 渲染toolBar
     * @returns {XML}
     */
    renderToolBar() {
        return (
            <Row className="table-toolbar">
                <Col span={12}>
                    <Link to="/order/start"><Button type="primary">代客下单</Button></Link>
                    <Button type="ghost" onClick={()=>this.startExportOrder()}>导出</Button>
                    <a href="http://fuwu.qianmi.com/fuwu/detail/FW_GOODS-10001139" target="_blank"><Button type="ghost">打印</Button></a>
                </Col>
            </Row>
        );
    }
    renderHeaderColumns() {
        const {filterKey, type} = this.props;
        let { filterDropdownVisible} = this.state;
        const _this = this;

        return  orderColumns(type).concat([{
                    title: orderStatus[filterKey],
                    width: 270,
                    key: 'state',
                    className:"ant-table-th-right pr8 va-t",
                    filterDropdown: (
                        <div className="w100 bd" style={{backgroundColor: '#fff'}}>{_this.renderButton()}</div>
                    ),
                    filterIcon: <Icon type="down-circle-o"/>,
                    filterDropdownVisible: filterDropdownVisible,
                    onFilterDropdownVisibleChange: visible=>_this.onFilterDropdownVisibleChange(visible)
                }]);
    }

    renderButton() {
        const {filterKey, type} = this.props;
        const orderStatusList = renderOrderFilter(type);

        return orderStatusList.map((status, index)=>{
            let {name, key} = status;
            let buttonCls = classNames('ml10 w80', {
                pusht: index == 0,
                pushb: orderStatusList.length == index + 1,
                mt5: index != 0
            });

            return <Button key={key}
                           className={buttonCls}
                           onClick={()=>this.changeOrderStatus(key)}
                           type={filterKey == key ? 'primary' : 'ghost'}>{name}</Button>
        })
    }

    /**
     * 切换不同订单状态列表
     * @param filterKey
     */
    changeOrderStatus(filterKey) {
        const {setOrderStatus, resetPagination} = this.props;
        setOrderStatus(filterKey);
        resetPagination();
        this.setState({
            filterDropdownVisible: false
        });
        this.queryOrderList();
    }
     /**
     * 全选操作
     * @param selected
     * @param selectedRows
     * @param changeRows
     */
    selectAll = (selected, selectedRows, changeRows) => {
        let selectedRowKeys = [];
        selected && selectedRows.forEach(row=>selectedRowKeys.push(row.tid));
        this.setState({selectedRowKeys});
    }
    /**
     * 过滤条件下拉框显示|隐藏
     * @param {*} visible 
     */
    onFilterDropdownVisibleChange(visible) {
        this.setState({
            filterDropdownVisible: visible
        })
    }
    renderRowHeader = (order) => {
        return (
            <Row>
                <Col span={18}>
                    <div className="order-info">
                        <p>
                            <span className="mr10">{`买家：${order.buyNickName}`}</span>
                            <span className="mr10 t-grayer">{`收货人：${order['consigneeInfo']['consigneeName']}`}</span>
                            <span className="mr10 t-grayer">{order['consigneeInfo']['consigneeMobile']
                            || order['consigneeInfo']['consigneePhone']}</span>
                        </p>
                        <p>
                            <span className="mr10">{`订单号：${order.tid}`}</span>
                            <span className="mr10 t-grayer">{order.payTypeName}</span>
                            <span className="mr10 t-grayer">{`配送方式：${order.shipMethodName}`}</span>
                            <span className="mr10 t-grayer">{`下单时间：${moment(order.ctime).format('YYYY/MM/DD HH:mm:ss')}`}</span>
                        </p>
                    </div>
                </Col>
                <Col span={6}>
                    <div className="t-right">
                        <p className="order-status lh36">{orderStatus[order.orderStatus]}</p>
                    </div>
                </Col>
            </Row>
        )
    }

    /**
     * 列渲染
     * @returns {string|Buffer|Array.<T>|*|{options, browsertest, dist, rhino, rhinolessc}}
     */
    renderSubColumns() {
        const { type} = this.props;
        //const {confirmLoading} = this.state;
        return orderColumns.concat([
            {
                title: '操作',
                width: 270,
                key: 'orderOpt',
                className:"ant-table-th-right pr8 va-t",
                render: (value, record, index) => {
                    return (
                        <div className="button-list">
                            <Link to={`/order/detail/${!!type && type.toLowerCase() === 'unpay' ? 'unpay' : 'sales'}/${record.tid}`}><Button type="ghost" className="pushl">看详情</Button></Link>
                            {this.renderOpts(record)}
                        </div>
                    )
                }
            }
        ])
    }
    /**
     * 订单状态对于不同操作
     * @returns {[XML,XML]}
     */
    renderOpts(record) {
        const { type} = this.props;
        const orderStatus = record.orderStatus;
        let opts = [];

        if (orderStatus === 'WAIT_PAY') {
            opts.push([
                <Popconfirm 
                    placement="topLeft"
                    title="确定取消订单吗？"
                    onConfirm={()=>this.cancelOrder(record)}><Button type="ghost" className="pushl">取消</Button></Popconfirm>
                , <Link to={`/order/edit/${!!type && type.toLowerCase() === 'unpay' ? 'unpay' : 'sales'}/${record.tid}`}><Button type="ghost" className="pushl">修改</Button></Link>
            ])
        } else if (orderStatus === 'WAIT_DELIVER' && record.deliverable) {
            opts.push([
                <Button type="ghost" className="pushl" onClick={()=>{this.refund(record)}}>申请退款</Button>
                , <Button type="ghost" className="pushl" onClick={()=>this.prepareDelivery(record)}>发货</Button>
            ])
        } else if (orderStatus === 'SUCCESS' && record.isApplyReturn == 1 && record.applyState == '0') {
            opts.push([
                <Link to={`/after/sales/${record.tid}`}><Button type="ghost" className="pushl">代客退货</Button></Link>
            ])
        }


        return opts;
    }
    /**
     * 弹出发货模态框，预备发货
     */
    prepareDelivery = (record) => {
        this.setState({
            activeOrder:Map(record),
            deliveryVisible:true
        });
    }

    /**
     * 发货操作
     * @param values
     */
    deliveryOrder(values) {
        this.setState({confirmLoading: true});
        this.props.deliveryOrder(values).then(()=>{
            this.cancelDeliveryOrder()
        }).catch(err=>{
            this.setState({
                confirmLoading: false
            });
        });
    }
    /**
     * 关闭发货模态框
     */
    cancelDeliveryOrder = () => {
         this.setState({
            deliveryVisible: false,
            activeOrder:Map({}),
            confirmLoading: false
        });
    }
    /**
     * 取消订单操作，弹出退款框
     */
    refund =(record)=>{
        const {refundBefore} = this.props;
        refundBefore(record.tid).then(()=>{
            this.showRefundModal(true);
        })
    }

    reimburse = (params)=>{
        return this.props.refund(params);
    }


    showRefundModal = (visible)=>{
        this.setState({
            refundVisible: visible
        })
    }

    /**
     * 取消订单
     */
    cancelOrder(record) {
        const {cancelOrder} = this.props;
        cancelOrder(record.tid);
    }
    /**
     * 选中|取消选中复选框
     * @param selectedRowKeys 选中的keys列表
     */
    handleSelect = (selectedRowKeys,selectedRows) => {
         this.setState({
            selectedRowKeys
        })
    }

     /**
     * 导出订单
     */
    startExportOrder() {
        const {selectedRowKeys} = this.state;
        if (selectedRowKeys.length) {
            this.props.startExportOrder(selectedRowKeys)
        }else {
            message.warn('请选择订单');
        }
    }

    queryOrderList() {
        this.setLoading(true);
        //查询订单列表
        this.props.queryOrderList().then(()=>{
            this.setLoading(false);
        }).catch(()=>{
            this.setLoading(false);
        });
    }
    changePageNum = (pageNum, pageSize) => {
        this.props.setPagination({pageNum})
        this.queryOrderList();
        this.scrollTop();
    }

    changePageSize = (current, pageSize) => {
        this.props.setPagination({pageNum:1,pageSize})
        this.queryOrderList();
        this.scrollTop();
    }
     /**
     * 设置loading状态
     * @param loading
     */
    setLoading = (loading)=>{
        this.setState({loading})
    }
}

export default OrderList;